<?php
/**
 * Created by PhpStorm.
 * User: tiemeng
 * Date: 16/1/8
 * Time: 15:18
 */
class groupActivityModel{
    private $_redisKey;
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        $this->_redisKey= REDIS_PREFIX."GAJoin_";

    }

    /**
     * 获取活动参加人数
     * @param $gid
     * @param $aid
     * @return mixed
     */
    public function joinNum($gid,$aid){
        $redisKey = $this->_redisKey.$gid."_".$aid;
        $num = intval($this->redis->ssize($redisKey));
        if($num <= 0){
            $num = $this->db->getOne("select count(1) from r_group_activity where gid=$gid and aid=$aid");
        }
        return $num;

    }

    /**
     * 活动列表
     * @param int $uid
     * @param string $aid
     * @param string $direc
     * @param int $offset
     * @return mixed
     */
    public function getMyActivity($uid,$aid='0',$direc='next',$offset=20){
        $redisKey = REDIS_PREFIX."MYActivity_".$uid;
        if(!$this->redis->exists($redisKey)){
            $this->_reData($uid);
        }
        if($aid > 0){
            if($direc == 'next')
            {
                $start = $this->redis->ZREVRANK($redisKey, $aid);
                $top = $start + $offset;
                $start += 1;
                $result = $this->redis->ZREVRANGE($redisKey, $start, $top);
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $aid);
                $top = $start + $offset;
                $start += 1;
                $result = $this->redis->ZRANGE($redisKey, $start, $top);
                !empty($result) && krsort($result);
            }
        }else{
            $result = $this->redis->zrevrange($redisKey,0,$offset);
        }
        return $result;

    }

    /**
     * 获取所有活动列表
     * @param int $aid
     * @param string $direc
     * @param int $offset
     * @return mixed
     */
    public function getActList($gid =0,$aid=0,$direc='next',$offset=20){
        $redisKey = REDIS_PREFIX."GroupActivity";
        $s = $offset - 1;
        if($gid > 0){
            $redisKey .= "_$gid";
        }
        if($aid > 0){
            if($direc == 'next')
            {
                $start = $this->redis->ZREVRANK($redisKey, $aid);
                $top = $start + $s;
                $start += 1;
                $result = $this->redis->ZREVRANGE($redisKey, $start, $top);
            }
            else
            {
                $start = $this->redis->ZRANK($redisKey, $aid);
                $top = $start + $s;
                $start += 1;
                $result = $this->redis->ZRANGE($redisKey, $start, $top);
                !empty($result) && krsort($result);
            }
        }else{
            $result = $this->redis->zrevrange($redisKey,0,$s);
        }
        if($gid == 0){
            $uid = $this->base->uid;
            if($aid > 0){
                $stime = $this->redis->hget(REDIS_PREFIX."ActivityInfo_".$aid,'stime');
                if($direc == 'next'){
                    $sql = "select a.aid from r_activity_add a left join r_group_activity ga on ga.aid=a.aid where type <=2 and a.uid!='$uid' and ga.status=0 and stime <$stime group by a.aid order by stime desc limit $offset";
                }else{
                    $sql = "select a.aid from r_activity_add a left join r_group_activity ga on ga.aid=a.aid where type <=2 and a.uid!='$uid' and ga.status=0 and stime >$stime group by a.aid  order by stime desc limit $offset";
                }
            }else{
                $sql = "select a.aid from r_activity_add a left join r_group_activity ga on ga.aid=a.aid where type <=2 and a.uid!='$uid' and ga.status=0  group by a.aid  order by stime desc limit $offset";
            }
            $result = $this->db->getAll($sql);
        }
        return $result;
    }



    /**
     * 检测用户是否加入某个活动
     * @param $aid
     * @param $uid
     * @param $gid
     * @return int
     */
    public function isJoin($aid,$uid,$gid){
        $redisKey = $this->_redisKey.$gid."_".$aid;
        $res = $this->redis->sIsMember($redisKey,$uid);
        return empty($res) ? 0 : 1;

    }

    public function isNotice($aid ,$uid, $gid)
    {
        $redisKey = REDIS_PREFIX . 'GANotice' .$gid."_".$aid;
        $res = $this->redis->sismember($redisKey, $uid);

        return $res ? 1 : 0;
    }

    public function addNotice($aid, $uid, $gid)
    {
        $redisKey = REDIS_PREFIX . 'GANotice' .$gid."_".$aid;
        $res = $this->redis->sadd($redisKey, $uid);

        return $res ? 1 : 0;
    }

    public function delNotice($aid, $gid)
    {
        $redisKey = REDIS_PREFIX . 'GANotice' .$gid."_".$aid;
        $res = $this->redis->del($redisKey);

        return $res ? 1 : 0;
    }

    public function getNotices($aid, $gid)
    {
        $redisKey = REDIS_PREFIX . 'GANotice' .$gid."_".$aid;

        return $this->redis->smembers($redisKey);
    }

    /**
     * 获取某个活动参加者
     * @param $gid
     * @param $aid
     * @param int $uid
     * @param string $direc
     * @param int $offset
     * @return mixed
     */
    public function getActJoins($gid,$aid,$id=0,$direc='next',$offset=20){
        $sql = "select id,uid,add_time from r_activity_add where gid=$gid and aid=$aid";
        if($id > 0){

            $sql .= " and id ";
            $sql .= $direc == 'prev' ? "> {$id} order by add_time ASC" : "< {$id} ORDER BY add_time DESC limit $offset";
        }
        else
        {
            $sql .= " ORDER BY add_time DESC limit $offset";
        }
        return $this->db->getAll($sql);
    }

    /**
     * 通过aid获取活动信息
     * @param $aid
     * @return mixed
     */
    public function getActByAid($aid){
        $result = $this->redis->hgetall(REDIS_PREFIX.'ActivityInfo_'.$aid);
        if(empty($result)){
            $sql = "select a.*,b.gift_id,b.gift_type,b.short_desc,b.rule,b.banner,b.cost_content from r_group_activity a left join r_office_activity b on a.aid=b.aid where a.aid='$aid'";
            $result =  $this->db->getRow($sql);
            !(empty($result)) && $this->redis->hmset(REDIS_PREFIX.'ActivityInfo_'.$aid,$result);
        }
        $result['target'] = strval($result['target']);
        if($this->base->vn >= 2730){
            $result['members'] = [];
            $result['banner'] = isset($result['banner']) ? json_decode($result['banner'],true) : [];
            $result['gift_type'] = isset($result['gift_type']) ? $result['gift_type'] : '';
            $result['gift_id'] = isset($result['gift_id']) ? $result['gift_id'] : 0;
            if(isset($result['type']) && ($result['type'] == 1 || $result['type'] == 3)){
                $result['days'] = ceil(($result['etime']-$result['stime'])/24/3600);
            }
            if(isset($result['gift_type']) && $result['gift_type'] == 2){
                $goodsId = $result['gift_id'];
                $goodsInfo = $this->base->load('goods')->getGoodsById($goodsId);
                $result['cost'] = isset($goodsInfo['price']) ? ($result['cost']+$goodsInfo['price']) : $result['cost'];
            }
        }

        return $result;

    }

    /**
     * 获取进行中的活动
     * @param $gid
     * @param int $aid 大于零时不包含ID
     * @param int $offset
     * @return mixed
     */
    public function getIngAct($gid,$aid=0,$offset=10){
        $time = time();
        $sql = "select * from r_group_activity where etime > $time and gid=$gid and status=0";
        if(!empty($aid)){
            $sql .= " and aid != $aid";
        }
        $sql .= " order by aid desc limit $offset";
        return $this->db->getAll($sql);
    }

    /**
     * 获取评论
     * @param $aid
     * @param int $cid
     * @param string $direc
     * @param int $offset
     * @return mixed
     */
    public function getCommend($aid,$cid=0,$direc='next',$offset=20){
        $sql = "select * from r_activity_comment where aid=$aid and is_show=1";
        if($cid > 0)
        {
            $sql .= " and cid ";
            $sql .= $direc == 'prev' ? "> {$cid} order by cid ASC" : "< {$cid} ORDER BY cid DESC limit $offset";
        }
        else
        {
            $sql .= " ORDER BY cid DESC limit $offset";
        }
        return $this->db->getAll($sql);
    }

    public function getContent($cid){
        $sql = "select content from r_activity_comment where cid=$cid";
        return $this->db->getOne($sql);
    }

    /**
     * 回复
     * @param $data
     * @return mixed
     */
    public function addComment($data){
        $img_size = empty($data['comment_img']) ? array() : getimagesize($_FILES['comment_img']['tmp_name']);
        $thumb_img = '';
        if(!empty($img_size) && !empty($comment_img))
        {
            $w = $img_size[0];
            $h = $img_size[1];
            $thumbInfo = $this->base->load('news')->getThumbInfo($w, $h);
            extract($thumbInfo);
            $thumb_img = empty($thumb_img) ? $comment_img : $comment_img .'?imageMogr2/thumbnail/'.$thumb_img;
        }
        $data['thumb_img'] = $thumb_img;
        $cid = $this->db->insertRowTable('r_activity_comment',$data);
        $this->db->query("update r_group_activity set total_comment = total_comment+1 where aid=". $data['aid']);
        $data['cid'] = $cid;
        return $data;

    }

    /**
     * 未开始活动
     * @param int $limit
     * @param $uid
     * @param string $city
     * @return array
     */
    public function nStartAct($limit = 10,$uid,$city=''){
        $time = time()+7200;
        $where = '';
        $aids = $this->redis->zrevrange(REDIS_PREFIX."MYActivity_".$uid,0,-1);
        $recAct = $this->redis->zrevrange(REDIS_PREFIX."ACTRecommend",0,-1);
        $aids = array_merge($recAct,$aids);
        if(!empty($aids)){
            $ids = implode(",",$aids);
            $where .= " and aid not in($ids)";
        }
        if(empty($city)){
            $sql = "select aid from r_group_activity where type<=2 and is_show=1 and stime > $time and status=0 $where order by type asc,total_comment desc,addtime desc limit $limit";
            $data =  $this->db->getAll($sql);
            $reData = [];
            foreach($data as $item){
                $info = $this->getActByAid($item['aid']);
                $reData[] = $info;
            }
        }else{
            $sql = "select aid from r_group_activity where type=0 and city='$city' and is_show=1 and stime > $time and status=0 $where order by total_comment desc,addtime desc limit $limit";
            $data = $this->db->getAll($sql);
            $count = count($data);
            $otherData = [];
            if(empty($data) || $count < $limit){
                $l = $limit - $count;
                $otherData = $this->db->getAll("select aid from r_group_activity where type >0 and type<=2 and is_show=1 and stime > $time and status=0 $where order by type asc,total_comment desc,addtime desc limit $l ");
            }
            $actIds = array_merge($data,$otherData);
            $reData = [];
            foreach($actIds as $item){
                $info = $this->getActByAid($item['aid']);
                $reData[] = $info;
            }
        }

        return $reData;

    }




    /**
     * 是否有进行中的活动
     * @param $gid
     * @param $uid
     * @return bool
     */
    public function isQuit($gid,$uid){
        $aids = $this->redis->zrangebyscore(REDIS_PREFIX."GroupActivity_".$gid,1000000,'+inf');
        $result = false;
        foreach($aids as $aid){
            if($this->redis->sismember(REDIS_PREFIX."GAJoin_".$gid."_".$aid,$uid)){
                $ainfo = $this->getActByAid($aid);
                if($ainfo['status'] == 0 && $ainfo['etime'] > time()){
                    $result = true;
                }
                break;
            }
        }
        return $result;

    }
    /**
     * 添加活动
     * @param $data
     * @return bool
     */
    public function addActivity($data){
        $add_time = time();
        $data['addtime'] = $add_time;
        $data['status'] = 0;
        $data['total_comment'] = 0;
        $data['url'] = "";
        $data['type'] = intval($data['type']);
        $data['is_show'] = intval($data['is_show']);
        $aid = $this->db->insertRowTable('r_group_activity',$data);
        if($aid > 0){
            $uid = $data['uid'];
            $gid = $data['gid'];
            $addData = compact('aid','uid','gid','add_time');
            $this->db->insertRowTable('r_activity_add',$addData); //插入活动参加表
            $data['aid'] = $aid;
            $redisKey = $this->_redisKey.$gid."_".$aid;
            $this->redis->sadd($redisKey,$uid);//用户加入活动
            $this->redis->hmset(REDIS_PREFIX.'ActivityInfo_'.$aid,$data);//活动详情
            //$data['is_show'] == 1 && $this->redis->zadd(REDIS_PREFIX."GroupActivity",$data['stime']+1000000000,$aid);  //所有活动
            $this->redis->zadd(REDIS_PREFIX."GroupActivity_".$gid,$data['stime']+1000000000,$aid); //某个群的活动
            $this->redis->zadd(REDIS_PREFIX."MYActivity_".$uid,$data['stime']+1000000000,$aid);//我的活动
            $this->base->load('xunSearch')->init('activity')->addIndex(array('aid'=>$aid,'title'=>$data['title']));

            //$userInfo = $this->base->load('client')->getUserInfo($uid);
            //$content = $data['nickname']." 发布了 ".$data['title'] ." 快快参加吧";
            //$this->base->load('message')->insertMessage(5,$uid,$gid,$uid,'InfoNtf',$content);
            $this->redis->lpush(REDIS_PREFIX."NewAct",$aid);
            $this->base->load('client')->userEnergyChange($uid,'createActivity',$aid);

        }
        return $aid;
    }

    /**
     * 获取群空间活动
     * @param int $gid
     * @param int $offset
     * @return mixed
     */
    public function getGRoomAct($gid,$offset=2){
        $time = time();
        $sql = "select aid from r_group_activity where (gid=$gid or type > 2) and status=0 and etime > $time order by type desc, addtime desc limit {$offset}";
        $data =  $this->db->getAll($sql);
        $reData = [];
        foreach($data as $item){
            $info = $this->getActByAid($item['aid']);
            $reData[] = $info;
        }
        return $reData;
    }

    public function quitAct($uid,$gid,$byself=false){
        //$time = time() + 7200;
        //$sql = "select aid from r_group_activity where uid=$uid and gid=$gid";
        $sql = "select aid from r_activity_add where uid=$uid and gid=$gid";
        $data = $this->db->getAll($sql);
        if(empty($data)){
            return false;
        }
        $message_id = $byself ? 'G24':'G22';
        $group_mod = $this->base->load('group');
        foreach($data as $item){
            $this->redis->srem(REDIS_PREFIX."GAJoin_".$gid."_".$item['aid'],$uid);
            $this->db->query("delete from r_activity_add where uid=$uid and gid=$gid and aid={$item['aid']}");
            $this->redis->zrem(REDIS_PREFIX."MYActivity_".$uid,$item['aid']);
            $group_mod->sendMessage([$uid],$gid,$message_id,0,$item['aid']);
            $this->db->query("delete from r_certificate where uid=$uid and gid=$gid and aid={$item['aid']}");
        }
    }

    public function _reData($uid){
        $data = $this->db->getAll("select aid,stime,status,etime from r_group_activity where uid=$uid");
        $ctime = time();
        foreach($data as $info){
            //未开始
            $time = $info['stime'];
            //结束
            if($info['etime'] < $ctime && $info['status'] == 0){
                $time = 1;
            }
            //正在进行中
            if($info['stime'] < $ctime && $ctime < $info['etime'] && $info['status'] == 0){
                $time = $info['stime'] + 1000000000;
            }
            //取消
            if($info['status'] == 1){
                $time = 0;
            }
            $this->redis->zadd(REDIS_PREFIX."MYActivity_".$uid,$time,$info['aid']);
        }
    }

    /**
     * 获取用户打卡天数
     * @param $aid
     * @param $gid
     * @param $uid
     * @param $target
     * @return int
     */
    public function getDays($aid,$gid,$uid,$target){
        $data = $this->redis->hgetAll(REDIS_PREFIX."UDPerDay_{$uid}_{$aid}_{$gid}");
        if(empty($data)){
            return 0;
        }
        $day = 0;
        foreach($data as $mileage){
            if($mileage >= $target){
                $day += 1;
            }
        }
        return $day;
    }

    /**
     * 竞赛类活动统计
     * @param $gid
     * @param $aid
     * @param int $offset_id
     * @param int $limit
     * @return array
     */
    public function actStatist($gid,$aid,$offset_id=0,$limit=10){
        $uid = $this->base->uid;
        $actInfo = $this->getActByAid($aid);
        $type = $actInfo['type'];//活动类型
        $target = $actInfo['target'];//目标
        $days = $actInfo['days']; //打卡天数
        //过滤自定义活动
        if(isset($actInfo['type']) && ($actInfo['type'] == 0 || $actInfo['type'] == 5)){
            return [
                'type'    => $type,
                'curUser' => (object)[],
                'target'  => $target,
                'days'    => $days,
                'members' => []
            ];
        }
        $isJoin = $this->isJoin($aid,$uid,$gid);
        $members = array();
        $data = $this->_getJoinMembers($aid,$gid,$actInfo,$offset_id,$limit);
        if($isJoin){
            $curUserInfo = $this->base->load('client')->getUserInfo($uid);
            $totalDay = $data['total_day'];
            //$total_mileage = strval($data['mileage']);
            $total_mileage = strval($this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid));
            if($type == 2){
                $result = $this->redis->zscore(REDIS_PREFIX."GADay_{$gid}_{$aid}",$uid);
                $curRank = $result>0 ? ($this->redis->zrevrank(REDIS_PREFIX."GADay_{$gid}_{$aid}",$uid) + 1) : 0;
                $finishNum = $totalDay;
                $offset = $curRank -2;
                $prev = $this->redis->zrevrange(REDIS_PREFIX."GADay_{$gid}_{$aid}",$offset,$offset,true);
                $prevFinishNum = current($prev);
                //$mileage = $this->getToalMileage(REDIS_PREFIX."UDPerDay_{$uid}_{$aid}_{$gid}",true);
                $mileage = $total_mileage;
            }else{
                $result = $this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid);
                $curRank = $result>0 ? ($this->redis->zrevrank(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid) + 1) : 0;
                $offset = $curRank -2;
                $prev = $this->redis->zrevrange(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$offset,$offset,true);
                $prevFinishNum = current($prev);
                $finishNum = $result;
                $mileage = $total_mileage;
            }
            if($curRank > 0){
                $curUser = [
                    'uid'       => $uid,
                    'header'    => $curUserInfo['header'],
                    'nickname'  => $curUserInfo['nickname'],
                    'mileage'   => $mileage,//今日里程/累积里程
                    'total_day' => $totalDay,
                    'rank'      => $curRank,
                    'content'   => $this->_rankDesc($actInfo,$curRank,$finishNum,$prevFinishNum),
                    'total_mileage' => $total_mileage
                ];
            }else{
                $curUser = (object)[];
            }

        }else{
            $curUser = (object)[];
        }
        foreach($data['ids'] as $id){
            $userInfo = $this->base->load('client')->getUserInfo($id);
            if(empty($userInfo)){
                continue;
            }
            $info['uid'] = $id;
            $info['header'] = $userInfo['header'];
            $info['nickname'] = $userInfo['nickname'];
            $info['mileage'] = 0;//今日里程/累积里程
            $info['total_day'] = 0;
            $info['total_mileage'] = strval($this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$id));
            if($actInfo['type'] == 2 || $actInfo['type'] == 4){
                $mileage = $actInfo['type'] == 2 ? $this->getToalMileage(REDIS_PREFIX."UDPerDay_{$id}_{$aid}_{$gid}",true) : $this->getToalMileage(REDIS_PREFIX."UDPerDay_{$id}_{$aid}_{$gid}");
                $info['mileage'] = strval($mileage);//今日里程/累积里程
                $info['total_day'] = $this->getDays($aid,$gid,$id,$target); //累计打卡/累计运动时间
                $info['rank'] = $this->redis->zrevrank(REDIS_PREFIX."GADay_{$gid}_{$aid}",$id) + 1;
            }else{
                $info['total_day'] = $this->redis->hlen(REDIS_PREFIX."UDPerDay_{$id}_{$aid}_{$gid}");
                $info['mileage'] = $info['total_mileage'];
                $info['rank'] = $this->redis->zrevrank(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$id) + 1;
            }
            $members[] = $info;
        }


        $reData = compact('type','curUser','target','days','members','isJoin');
        return $reData;
    }

    /**
     * 参加活动用户
     * @param $aid
     * @param $gid
     * @param $actInfo
     * @param int $offset_id
     * @param int $limit
     * @return array
     */
    private function _getJoinMembers($aid,$gid,$actInfo,$offset_id=0,$limit=10){
        $uid = $this->base->uid;
        $start = 0;
        if($actInfo['type'] == 2){
            if($offset_id > 0){
                $start = $this->redis->zrevrank(REDIS_PREFIX."GADay_{$gid}_{$aid}",$offset_id) + 1;
                $limit = $limit + $start;
            }
            $ids = $this->redis->zrevrange(REDIS_PREFIX."GADay_{$gid}_{$aid}",$start,$limit - 1);
            $total_day = $this->getDays($aid,$gid,$uid,$actInfo['target']);
            $mileage = strval($this->getToalMileage(REDIS_PREFIX."UDPerDay_{$uid}_{$aid}_{$gid}"));
        }else{
            if($offset_id > 0){
                $start = $this->redis->zrevrank(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$offset_id) + 1;
                $limit = $limit + $start;
            }
            $ids = $this->redis->zrevrange(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$start,$limit-1);
            $total_day = $this->redis->hlen(REDIS_PREFIX."UDPerDay_{$uid}_{$aid}_{$gid}");
            $mileage = floatval($this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid));
        }
        return compact('ids','total_day','mileage');
    }

    /**
     * 获取官方活动奖品名称
     * @param $aid
     * @return string
     */
    public function getGiftName($aid){
        $data = $this->getActByAid($aid);
        $name = '';
        if(isset($data['gift_id']) && $data['gift_id'] > 0){
            if($data['gift_type'] == 1){
                $medalInfo = $this->base->load('medal')->getMedalInfo($data['gift_id']);
                $name = isset($medalInfo['medal_name']) ? $medalInfo['medal_name'] : '';
            }else{
                $goodsInfo = $this->base->load('goods')->getGoodsById($data['gift_id']);
                $name = isset($goodsInfo['goods_name']) ? $goodsInfo['goods_name'] : '';
            }

        }
        return $name;
    }

    /**
     * 活动动态
     * @param $aid
     * @return array
     */
    public function trend($aid){
        $groups = $this->redis->smembers(REDIS_PREFIX."ACTaccept_".$aid);
        $reData[] = '战鼓已经擂响 没你不行！';
        if(empty($groups)){
            return $reData;
        }
        foreach($groups as $gid){
            $groupName = $this->redis->hget(REDIS_PREFIX."GroupInfo_".$gid,'name');
            $data[] = '"'.$groupName.'"已参赛，速来报名参加，争排名得奖品';
        }
        return $data;
    }

    /**
     * 官方活动群排行
     * @param $aid
     * @param int $gid
     * @param int $limit
     * @return array
     */
    public function groupRank($aid,$id=0,$limit=10){
        $start = 0;
        if($id > 0){
            $start = $this->redis->zrevrank(REDIS_PREFIX.'GroupAct_'.$aid,$id) + 1;
            $limit = $start + $limit;
        }
        $list = $this->redis->zRevRange(REDIS_PREFIX.'GroupAct_'.$aid,$start,$limit-1,true);
        $reData = [];
        if(empty($list)){
            return $reData;
        }
        foreach($list as $gid=>$mileage){
            $gInfo = $this->base->load('group')->getGroupInfo($gid);
            $reData[] = [
                'header'  => $gInfo['header'],
                'name'    => $gInfo['name'],
                'rank'    => $this->redis->zrevrank(REDIS_PREFIX.'GroupAct_'.$aid,$gid) + 1,
                'mileage' => strval($mileage),
                'gid'     => strval($gid)
            ];
        }
        return $reData;
    }

    /**
     * 添加申诉
     * @param $name
     * @param $desc
     * @param $aid
     * @return mixed
     */
    public function addComplain($name,$reason,$aid){
        $uid = $this->base->uid;
        $img = array();
        //允许最多上传5张
        for($i=0;$i<=4;$i++){
            if (isset($_FILES["img_".$i]) && $_FILES['img_'.$i]['error'] == 0 && in_array($_FILES['img_'.$i]['type'], array('image/png', 'image/gif', 'image/jpeg')))
            {
                $name = md5(time().$i.common::getHashStr(5));
                $imgUrl = $this->base->load('qiniu')->uploadQiNiuImg('img_'.$i, $name);
                $img[] = $imgUrl;
            }
        }
        $img = json_encode($img);
        $addtime = time();
        $data = compact('aid','uid','name','img','reason','addtime');
        return $this->db->insertRowTable('r_complain',$data);
    }

    /**
     * 官方活动banner
     * @return array|mixed
     */
    public function getActBanner(){
        return $this->base->load('banner')->getActBanner();
    }

    /**
     * 证书名次文案
     * @param $rankType
     * @param int $mileage
     * @return mixed
     */
    public function getDesc($rankType,$mileage=0){
        $desc = [
            "最“脚勤”的“健人”\n力压群雄  根本停不下来",
            "无冕之王\n离冠军只差'.$mileage.'公里  加冕指日可待",
            "最牛的季军\n荣登三甲   用脚步丈量高度",
            "遗憾也是一种美\n除了三甲 你们最牛",
            "希望就在前方\n季军只能憧憬冠军 而你有千万种可能"
        ];
        return $desc[$rankType];
    }

    /**
     * 检测活动开始是否为两小时内
     * @param $stime
     * @return bool
     */
    public function isHandle($stime){
        if($stime > (time() - 7200)){
            return true;
        }
        return false;
    }

    /**
     * 获取用户某个活动的跑步总里程
     * @param $key
     * @return float|int
     */
    public function getToalMileage($key,$today=false){
        $data = $this->redis->hgetAll($key);
        if(empty($data)){
            return 0;
        }
        if($today){
            $todayBegin = date('Ymd');
            foreach($data as $date=>$v){
                if($date < $todayBegin){
                    unset($data[$date]);
                }
            }
        }
        return sprintf("%.2f",array_sum($data));
    }

    private function _rankDesc($actInfo,$rank,$finishNum=0,$prevFinishNum=0){
        if(empty($actInfo) || !in_array($actInfo['type'],[1,2])){
            return "";
        }
        $time = time();
        if($actInfo['type'] == 1){//里程
            $target = $actInfo['target'];
            //活动进行中
            if($actInfo['stime'] < $time && $time < $actInfo['etime']){
                if($target <= $finishNum){
                    $mileage = number_format(($prevFinishNum-$finishNum),3);
                    $mileage = $mileage > 0 ? $mileage : 0;
                    $content = $mileage ? "距离上一名只差".$mileage."公里，继续加油吧！" : "太棒了，您的目标已经完成，力压群雄！";
                }else{
                    $content = '成功在于坚持，不放弃，你会看到不一样的自己！';
                }
            }else{
                if($target <= $finishNum){
                    switch($rank){
                        case 1:
                            $content = '太棒了，您在本次活动力压群雄，获得了冠军宝座！';
                            break;
                        case 2:
                            $content = '太棒了，您在本次活动获得了亚军，冠军指日可待！';
                            break;
                        case 3:
                            $content = '太棒了，您在本次活动获得了季军， 冠军指日可待！';
                            break;
                        default:
                            $content = '太棒了，您的目标已经完成！你已经超越90%的人';
                    }
                }else{
                    $content = "成功在于坚持，不放弃，你会看到不一样的自己！";
                }
            }
        }else{ //打卡
            $target = $actInfo['days'];
            if($actInfo['stime'] < $time && $time < $actInfo['etime']){
                if($target <= $finishNum){
                    $day = ($prevFinishNum-$finishNum);
                    $day = $day > 0 ? $day : 0;
                    $content = "距离上一名只差".$day."天，继续加油吧！";
                }else{
                    $content = "成功在于坚持，不放弃，你会看到不一样的自己！";
                }
            }else{
                if($target <= $finishNum){
                    $content = '太棒了，目标已完成！你已经超越90%的人！';
                }else{
                    $mileage = number_format(($target-$finishNum),3);
                    $content = "距离完成目标只差".$mileage."天，别气馁，下次一定成功！";
                }
            }

        }

        return $content;
    }
    
    /*
     * 取消活动
     */
    public function cancelActivity($aid,$gid){
        $agid = $this->redis->hget(REDIS_PREFIX."ActivityInfo_".$aid,'gid');
        //非官方活动
        if($agid){
            $sql = "update r_group_activity set status=1 where gid=$gid and aid=$aid";
            $this->base->load('xunSearch')->init('activity')->delIndex($aid,'aid');
            $this->db->query($sql);
            $this->redis->zrem(REDIS_PREFIX."ACTRecommend",$aid);//取消活动推荐列表中移除
            //$this->redis->zadd(REDIS_PREFIX."GroupActivity",0,$aid);  //所有活动
            $this->redis->zadd(REDIS_PREFIX."GroupActivity_".$gid,0,$aid); //某个群的活动
            $this->redis->hset(REDIS_PREFIX."ActivityInfo_".$aid,'status',1);
            $this->base->load('group')->sendMessage($members,$gid,'G13',0,$aid);
        }
        $members = $this->redis->smembers(REDIS_PREFIX."GAJoin_".$gid."_".$aid);
        foreach($members as $id){
            $this->redis->zadd(REDIS_PREFIX."MYActivity_".$id,0,$aid);
        }
    }
    
    /*
     * 获得证书列表
     */
    public function getCertificates($uid,$id,$direc='next',$offset=20,$act_type=null){
        $sql = "select c.* from r_certificate c left join r_group_activity on r_group_activity.aid = c.aid";
        $where = " where c.uid=$uid";
        if($act_type===0){
            $where .= ' and (c.act_type=0 and (`type`=1 or `type`=2))';
        }elseif($act_type==1){
            $where .= ' and c.act_type=1';
        }elseif($act_type===null){
            $where .= ' and (c.act_type=1 or (c.act_type=0 and (`type`=1 or `type`=2)))';
        }
        if($direc=='next'){
            $id && $where .= " and c.id < $id";
            $order = ' order by c.id desc';
        }else{
            $id && $where .= " and c.id > $id";
            $order = ' order by c.id asc';
        }
        
        return $this->db->getAll($sql.$where.$order." limit $offset");
    }
    
    /*
     * 或者证书张数
     * 当$id=0 时，返回总数
     */
    public function getCertificateNo($uid,$id=0){
        $sql = "select count(*) from r_certificate c left join r_group_activity on r_group_activity.aid = c.aid where c.uid=$uid and (c.act_type=1 or (c.act_type=0 and (`type`=1 or `type`=2)))";
        if($id){
            $sql .= " and c.id<$id";
        }
        $no = $this->db->getOne($sql);
        return $id ? $no+1 : $no;
    }
    
    /*
     * 用id获取证书内容
     */
    public function getCertificateInfoById($id){
        $reData = $this->db->getRow($sql = "select * from r_certificate where id=$id limit 1");
        if($reData){
            $reData['no'] = $this->getCertificateNo($reData['uid'],$reData['id']);
            return $reData;
        }
        return [];
    }
    
    /*
     * 获得证书内容
     */
    public function getCertificateInfo($aid,$gid,$uid,$for='select'){
        if(!$this->isJoin($aid,$uid,$gid)){
            return [];
        }
        
        //目的是写数据库时，不从数据库读
        if($for != 'update'){
            $reData = $this->db->getRow($sql = "select * from r_certificate where aid=$aid and gid=$gid and uid=$uid limit 1");
        }
        
        if(!empty($reData)){
            $reData['no'] = $this->getCertificateNo($uid,$reData['id']);
            return $reData;
        }
        $no = $this->getCertificateNo($uid)+1;
        $userInfo = $this->base->load('client')->getUserInfo($uid);
        $actInfo = $this->getActByAid($aid);
        $groupInfo = $this->base->load('group')->getGroupInfo($gid);
        $img = "";
        if($actInfo['type'] > 2 && isset($actInfo['gift_type'])){
            if($actInfo['gift_type'] == 1 && $actInfo['gift_id'] > 0){
                $img = "http://".$this->base->config['host']."/static/backend/medal/".$actInfo['gift_id'].'.png';
            }else{
                $goodsInfo = $this->base->load('goods')->getGoodsById($actInfo['gift_id']);
                isset($goodsInfo['thumb']) && $img = $goodsInfo['thumb'];
            }
        }
        $day = $this->getDays($aid,$gid,$uid,$actInfo['target']);
        $mileage = floatval($this->redis->zscore(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid));
        
        $run_mod = $this->base->load('run');
        $reData = [
            'aid' => $aid,
            'gid '=> $gid,
            'uid' => $uid,
            'no' => $no,
            'day' => $day,
            'farthest' => floatval($run_mod->getMileageByTime($uid,$actInfo['stime'],$actInfo['etime'])),
            'max_speed' => floatval($run_mod->getMaxSpeedByTime($uid,$actInfo['stime'],$actInfo['etime'])),
            'total_elapsedtime' => floatval($run_mod->getTotalElapsedtime($uid,$actInfo['stime'],$actInfo['etime'])),
            'mileage' => $mileage,
            'nickname' => isset($userInfo['cer_nickname']) ? $userInfo['cer_nickname'] : $userInfo['nickname'],
            'header' => isset($userInfo['cer_header']) ? $userInfo['cer_header'] : $userInfo['header'],
            'groupName' => $groupInfo['name'],
            'img' => $img,
            'addtime' => $actInfo['etime'],
            'act_type' => 0
        ];
        if($actInfo['type'] == 2 || $actInfo['type'] == 4){//打卡
            if($day >= $actInfo['days']){//完成打卡
                $reData['isFinish'] = 1;
                $reData['rank']     = 0;
            }else{
                $reData['isFinish'] = 0;
                $reData['rank']     = 0;
            }
        }else{
            $rank = $this->redis->zrevrank(REDIS_PREFIX."GARecord_{$gid}_{$aid}",$uid) + 1;
            $target = $actInfo['target'];
            if($mileage >= $target){
                $is_finish = 1;
            }else{
                $is_finish = 0;
            }
            $reData['isFinish']  = $is_finish;
            $reData['rank']     = $rank;
        }
        $reData['cid'] = intval($this->db->getRow("select aid from r_complain where aid=$aid"));
        
        return $reData;
    }
    
    /*
     * 修改证书个人信息
     */
    public function putCertificate($id,$uid,$nickname,$header){
        $nickname && $set['nickname'] = $nickname;
        $header && $set['header'] = $header;
        
        if(empty($set)){
            return false;
        }
        $set['uid'] = $uid;
        $set['id'] = $id;
        $res = $this->db->updateRowTable('r_certificate',$set);
        
        if(!$res){
            return;
        }
        $user = [];
        $nickname && $user['cer_nickname'] = $nickname;
        $header && $user['cer_header'] = $header;
        $res = $this->db->getRowTable('r_user_ext',['cer_header','cer_nickname'],'uid='.$uid);
        $this->base->load('user')->setUserExt($uid,$user);
        
        //第一次提交，修改所有证书昵称
        if(!$res['cer_header'] && !$res['cer_nickname']){
            $sql = 'update r_certificate set';
            $nickname && $sql .= " nickname = '$nickname'";
            if($header){
                $nickname && $sql .= " ,";
                $sql .= " header = '$header'";
            }
            $this->db->update($sql." where uid=$uid");
        }
    }

}